package cn.rubintry.bug.hunting.fragment

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.core.os.bundleOf
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewbinding.ViewBinding
import cn.rubintry.bug.common.base.BaseFragment
import cn.rubintry.bug.hunting.R
import cn.rubintry.bug.hunting.activity.ArticleDetailActivity
import cn.rubintry.bug.hunting.adapter.ArticleListAdapter
import cn.rubintry.bug.hunting.databinding.FragmentHomeBinding
import cn.rubintry.bug.hunting.decoration.VerticalSpaceItemDecoration
import cn.rubintry.bug.hunting.common.extension.paddingTop
import cn.rubintry.bug.hunting.common.http.viewmodel.HomeViewModel

import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.ToastUtils


/**
 * 首页
 */
class HomeFragment() : BaseFragment<FragmentHomeBinding>() {
    private val homeViewModel: HomeViewModel by viewModels<HomeViewModel>()


    private var homeArticleAdapter : ArticleListAdapter ?= null


    /**
     * 当前页码
     */
    private var curPageNum = 1

    /**
     * 每页显示的条数
     */
    private val PAGE_SIZE = 10

    override fun layoutId(): Int {
        return R.layout.fragment_home
    }


    override fun initView() {
        binding?.tlHomeTitle?.paddingTop(BarUtils.getStatusBarHeight())

        //初始化文章列表
        binding?.rvArticleList?.layoutManager = LinearLayoutManager(requireContext())
        binding?.rvArticleList?.isNestedScrollingEnabled = false
        homeArticleAdapter = ArticleListAdapter(mutableListOf())
        binding?.rvArticleList?.adapter = homeArticleAdapter

        homeArticleAdapter?.setOnItemClickListener { adapter, view, position ->
            val item = adapter.getItem(position)
            val intent = Intent(requireContext() , ArticleDetailActivity::class.java)
            val params = bundleOf(
                Pair("articleId", item?.id ?: "")
            )
            intent.putExtras(params)
            startActivity(intent)
        }

        //设置刷新监听
        binding?.refreshArticleList?.setOnRefreshListener {
            getNetData(true)
        }
        //设置加载更多监听器
        binding?.refreshArticleList?.setOnLoadMoreListener {
            getNetData(true , true)
        }
    }



    override fun observeData() {
        homeViewModel.articleData.observe(this) { data ->
            if(data.code == "0"){
                if(binding?.rvArticleList?.itemDecorationCount == 0){
                    binding?.rvArticleList?.addItemDecoration(VerticalSpaceItemDecoration(15 , data.total.toInt()))
                }
                if(data.loadMore){
                    data?.data?.let {
                        homeArticleAdapter?.addAll(it)
                        binding?.refreshArticleList?.finishLoadMore(0 , true , it.isEmpty())
                    }
                }else{
                    homeArticleAdapter?.submitList(data?.data)
                }

            }else{
                ToastUtils.showShort("请求失败：" + data.message)
            }
            binding?.refreshArticleList?.finishRefresh()

        }
    }


    override fun bindingClazz(): Class<out ViewBinding> {
        return FragmentHomeBinding::class.java
    }

    override fun onNetWorkError(msg: String) {

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        getNetData(false)
    }

    /**
     * 获取网络数据
     * @param fromRefreshing 是否由下拉刷新触发
     */
    private fun getNetData(fromRefreshing: Boolean , loadMore: Boolean = false) {
        if(loadMore){
            curPageNum ++
        }else
            curPageNum = 1
        //获取文章列表
        homeViewModel.getArticleWithLimit((curPageNum - 1) * PAGE_SIZE , PAGE_SIZE , fromRefreshing , loadMore)

    }

    override fun onStop() {
        super.onStop()
//        binding?.banner?.stop()
    }
}